package com.hgc.ch03;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * Created by 01367627 on 2019/7/10.
 */
public class AtomicStampedReferenceExample {

    private static AtomicStampedReference<String> asr = new AtomicStampedReference<>("huanggc",0);
    private static CountDownLatch latch = new CountDownLatch(10);

    private static class MyRunnable implements Runnable{
        @Override
        public void run() {
            String ref = asr.getReference();
            int stamp = asr.getStamp();
            if(asr.compareAndSet(ref,ref+Thread.currentThread().getName(),stamp,stamp+1)){
                System.out.println(Thread.currentThread().getName() + "修改成功");
            }else{
                System.out.println(Thread.currentThread().getName() + "修改失败");
            }
            latch.countDown();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyRunnable runnable = new MyRunnable();
        for(int i=0;i<10;i++){
            new Thread(runnable,"t" + i).start();
        }
        latch.await();
        System.out.println(asr.getReference());
        System.out.println(asr.getStamp());
    }

}
